package controller

import (
	"gitee.com/crack007/api-throttling/common/exception"
	"gitee.com/crack007/api-throttling/dto"
	"gitee.com/crack007/api-throttling/service"
	"gitee.com/crack007/goose/throttle"
	"github.com/gin-gonic/gin"
	"strconv"
)

type ApiController struct {
}

func (c *ApiController) AddUser(ctx *gin.Context) interface{} {
	userDto := &dto.UserDto{}
	err := ctx.ShouldBind(&userDto)
	if err != nil {
		return exception.NewApiException(err.Error(), 400)
	}
	apiService := service.ApiManager.GetRoute(userDto.RouteName)
	if apiService == nil {
		return exception.NewApiException("路由不存在", 404)
	}
	apiService.ApiThrottle.AddThrottle(throttle.NewThrottleConfig(userDto.Id, userDto.Limit, userDto.MaxBucket))
	return nil
}

func (c *ApiController) DelUser(ctx *gin.Context) interface{} {
	routeName, _ := ctx.GetQuery("route")
	id, _ := ctx.GetQuery("id")
	apiService := service.ApiManager.GetRoute(routeName)
	if apiService == nil {
		return exception.NewApiException("路由不存在", 404)
	}
	uid, _ := strconv.Atoi(id)
	if !apiService.ApiThrottle.RemoveId(int64(uid)) {
		return exception.NewApiException("id不存在或已删除", 404)
	}
	return nil
}

func (c *ApiController) UpdateUser(ctx *gin.Context) interface{} {
	userDto := &dto.UserDto{}
	err := ctx.ShouldBind(&userDto)
	if err != nil {
		return exception.NewApiException(err.Error(), 400)
	}
	userDto.RouteName, _ = ctx.GetQuery("route")
	apiService := service.ApiManager.GetRoute(userDto.RouteName)
	if apiService == nil {
		return exception.NewApiException("路由不存在", 404)
	}
	apiService.ApiThrottle.UpdateThrottle(throttle.NewThrottleConfig(userDto.Id, userDto.Limit, userDto.MaxBucket))
	return nil
}
